package com.example.yuecvideo.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.example.yuecvideo.R;
import com.example.yuecvideo.utils.ImageSaveUtil;
import com.example.yuecvideo.utils.ScreenUtil;
import com.example.yuecvideo.utils.ToastUtil;

import org.opencv.android.OpenCVLoader;
import java.io.File;

import java.io.IOException;


public class PicModifyActivity extends AppCompatActivity {
    /// 各个文字控件
    private TextView return_view, picInfo_view, picModify_view;
    /// ImageView控件
    private ImageView imageView;
    /// 图像的路径
    String imageUri;

    /// 图像的宽，高
    String imageWidth, imageHeight;

    private int choice;  // radio的选项

    private boolean isChecked;// 是否保持横纵比
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        OpenCVLoader.initDebug();  /// 这条语句及其重要，使用opencv时要进行初始化
        setContentView(R.layout.activity_pic_modify);
        init();
    }

    private void init() {
        imageUri = getIntent().getStringExtra("uri");
        return_view = (TextView) findViewById(R.id.pic_modify_return);
        picInfo_view = (TextView) findViewById(R.id.pic_modify_picInfo);
        picModify_view = (TextView) findViewById(R.id.pic_modify_modify);
        imageView = (ImageView) findViewById(R.id.pic_modify_ImgView);
        return_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish();
            }
        });
        picModify_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.ShowText(imageUri, getApplicationContext());

                ContentResolver resolver = getContentResolver();
                try {
                    getPicInfo(Uri.parse(imageUri));
                    dialog();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        imageView.setImageURI(Uri.parse(imageUri));
        String[] info = imageUri.toString().split("/");
        picInfo_view.setText(info[info.length - 1]);

    }

    private void getPicInfo(Uri uri) throws IOException {
        ContentResolver resolver = getContentResolver();
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(resolver, uri);
        imageWidth = "" + bitmap.getWidth();
        imageHeight = "" + bitmap.getHeight();
    }


    private void dialog() {
        View view = LayoutInflater.from(this).inflate(R.layout.hight_option_dialog_layout, null, false);
        final AlertDialog dialog = new AlertDialog.Builder(this).setView(view).create();

        Button btn_cancel_high_opion = view.findViewById(R.id.btn_cancel_high_opion);
        Button btn_agree_high_opion = view.findViewById(R.id.btn_agree_high_opion);

        EditText verticalEdit = view.findViewById(R.id.vertical_num);
        EditText horizontalEdit = view.findViewById(R.id.horizontal_num);
        RadioGroup radioGroup = view.findViewById(R.id.radio_group);
        RadioButton ratioRadioButton = view.findViewById(R.id.radio_ratio);
        RadioButton pixelRadioButton = view.findViewById(R.id.radio_pixel);
        CheckBox keepCheck = view.findViewById(R.id.keep_ratio);
        choice = radioGroup.getCheckedRadioButtonId();

        horizontalEdit.setText(imageWidth);
        verticalEdit.setText(imageHeight);
        ratioRadioButton.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onClick(View v) {
                verticalEdit.setText("100");
                horizontalEdit.setText("100");
                choice = ratioRadioButton.getId();
            }
        });

        pixelRadioButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                horizontalEdit.setText(imageWidth);
                verticalEdit.setText(imageHeight);
                choice = pixelRadioButton.getId();
            }
        });
        btn_cancel_high_opion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        btn_agree_high_opion.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("NonConstantResourceId")
            @Override
            public void onClick(View v) {
                switch (choice) {
                    case R.id.radio_ratio:
                        try {
                            Log.i("go", "doModifyByRatio");
                            doModifyByRatio(horizontalEdit.getText().toString(), verticalEdit.getText().toString());
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                        break;
                    case R.id.radio_pixel:
                        try {
                            Log.i("go", "doModifyByPixel");
                            doModifyByPixel(horizontalEdit.getText().toString(), verticalEdit.getText().toString());
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                        break;
                    default:
                        break;
                }
                dialog.dismiss();
            }
        });
        horizontalEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                if (isChecked) {
                    switch (choice) {
                        case R.id.radio_ratio:
                            verticalEdit.setText(horizontalEdit.getText().toString());
                            break;
                        case R.id.radio_pixel:
                            int ratio = Integer.parseInt(imageWidth) / Integer.parseInt(imageHeight);
                            Log.i("ratio", ""+ratio);
                            verticalEdit.setText(Integer.parseInt(horizontalEdit.getText().toString()) / ratio);
                            break;
                        default:
                            break;
                    }
                }
            }
        });


        keepCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isCheck) {
                isChecked = isCheck;
            }
        });
        dialog.show();
        //此处设置位置窗体大小，我这里设置为了手机屏幕宽度的3/4  注意一定要在show方法调用后再写设置窗口大小的代码，否则不起效果会
        dialog.getWindow().setLayout((ScreenUtil.getScreenWidth(this) / 4 * 3), LinearLayout.LayoutParams.WRAP_CONTENT);
    }

    /**
     * @brief 根据比例来修改图片
     */
    private void doModifyByRatio(String horizontal_ratio, String vertical_ratio) throws IOException {

        int width = (int) (Integer.parseInt(imageWidth) * 0.01 * Integer.parseInt(horizontal_ratio));
        int height = (int) (Integer.parseInt(imageHeight) * 0.01 * Integer.parseInt(vertical_ratio));
        ContentResolver resolver = getContentResolver();
        File file = ImageSaveUtil.Save(resolver, imageUri, width, height);
        MediaScannerConnection.scanFile(this, new String[]{file.getAbsolutePath()}, null, null);
        ToastUtil.ShowText("修改成功", getApplicationContext());
        finish();
    }

    /**
     * @brief 根据像素来修改图片
     */
    private void doModifyByPixel(String width, String height) throws IOException {
        ContentResolver resolver = getContentResolver();
        File file = ImageSaveUtil.Save(resolver, imageUri, Integer.parseInt(width), Integer.parseInt(height));
        // 最后，更新相册
        MediaScannerConnection.scanFile(this, new String[]{file.getAbsolutePath()}, null, null);
        ToastUtil.ShowText("修改成功", getApplicationContext());
        finish();

    }


}